package com.sdhillon.mappercentwidth.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.layout.client.Layout.AnimationCallback;
import com.google.gwt.layout.client.Layout.Layer;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;

/**
 * @author Sunny Dhillon
 * This class demonstrates how to fill a parent container with a map. 
 * Using a ResizeHandler and adding a zero second animation to the
 * RootLayoutPanel handles the cases of the user resizing the browser and
 * the initial load up of the application.
 */
public class MapPercentWidth implements EntryPoint, ResizeHandler {

	interface Binder extends UiBinder<DockLayoutPanel, MapPercentWidth> {
	}

	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField
	MapWidget map;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		// Create the UI defined in MapPercentWidth.ui.xml.
		DockLayoutPanel panel = binder.createAndBindUi(this);

		// Get rid of scrollbars, and clear out the window's built-in margin,
		// because we want to take advantage of the entire client area.
		Window.enableScrolling(false);
		Window.setMargin("0px");
		
		// Zoom in a bit
		map.setCenter(LatLng.newInstance(37.352693,-121.896057), 7);
		
		// Add the outer panel to the RootLayoutPanel, so that it will be
		// displayed.
		RootLayoutPanel root = RootLayoutPanel.get();
		root.add(panel);
		
		// The map needs to be resized once rendering has completed because
		// the layout has not finalized yet. onAnimationComplete will be fired
		// after rendering allowing us to resize the map to fill its parent.
		root.animate(0, new AnimationCallback() {
			@Override
			public void onLayout(Layer layer, double progress) {
			}
			
			@Override
			public void onAnimationComplete() {
				resizeMap();
			}
		});
	}

	@Override
	public void onResize(ResizeEvent event) {
		// resize the map to the new height and width of the browser
		resizeMap();
	}

	/**
	 * Resize the map to fill the parent container, equivalent for setting
	 * the map's width='100%' and height='100%'.
	 */
	private void resizeMap() {
		map.setSize(map.getParent().getOffsetWidth() + "px", map.getParent()
				.getOffsetHeight()
				+ "px");
	}
}
